﻿using System;
using UnityEngine;

namespace ChivalryUnity.Mvc
{
    public class MvcView : MonoBehaviour
    {
        protected MvcMediator m_mediator;

        private void Awake()
        {
            BindMediator();

            if (m_mediator != null)
                m_mediator.Init(this);

            OnViewAwake();
        }
        protected virtual void OnViewAwake() { }

        private void OnDestroy()
        {
            if (m_mediator != null)
                m_mediator.Destroy();

            OnViewDestroy();
        }
        protected virtual void OnViewDestroy() { }

        private void BindMediator()
        {
            Type type = GetType();
            object[] attrs = type.GetCustomAttributes(typeof(MvcBindAttribute), false);
            if (attrs.Length > 0)
            {
                MvcBindAttribute attr = attrs[0] as MvcBindAttribute;
                MvcMediator mediator = Activator.CreateInstance(attr.MediatorType) as MvcMediator;
                if (mediator == null)
                    return;

                m_mediator = mediator;
            }
        }
    }
}